package com.zh.onlineexam.util;

import cn.hutool.core.util.ObjectUtil;
import com.zh.onlineexam.common.CacheConstants;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.function.Supplier;

/**
 * @author 29934
 */
@Component
public class LoginUtil {

    /**
     * 登录校验
     *
     * @param userName  用户名
     * @param supplier  执行函数
     */
    public String checkLogin(String userName, Supplier<Boolean> supplier){
        String errorKey = CacheConstants.LOGIN_ERROR + userName;
        StringBuffer stringBuffer = new StringBuffer();
        //获取用户登录错误次数
        Integer errorCount;
        errorCount = RedisUtil.getCacheObject(errorKey) == null ? 0 : RedisUtil.getCacheObject(errorKey);
        if (errorCount>=CacheConstants.LOGIN_ERROR_COUNT){
            RedisUtil.setCacheObject(errorKey, errorCount, Duration.ofMinutes(CacheConstants.LOGIN_ERROR_LIMIT_TIME));
            stringBuffer.append("您的账号已被锁定，请").append(Duration.ofMinutes(CacheConstants.LOGIN_ERROR_LIMIT_TIME).getSeconds()).append("S后重试");
            return stringBuffer.toString();
        }
        if (supplier.get()){
            // 是否第一次登录，不是的话计数+1
            errorCount = ObjectUtil.isNull(errorCount) ? 1 : errorCount + 1;
            // 达到限定错误次数，锁定登录
            if (errorCount>=CacheConstants.LOGIN_ERROR_COUNT){
                RedisUtil.setCacheObject(errorKey, errorCount, Duration.ofMinutes(CacheConstants.LOGIN_ERROR_LIMIT_TIME));
                stringBuffer.append("您的账号已被锁定，请").append(Duration.ofMinutes(CacheConstants.LOGIN_ERROR_LIMIT_TIME).getSeconds()).append("S后重试");
            }else{
                // 未达到限定错误次数，递增次数
                RedisUtil.setCacheObject(errorKey, errorCount);
                stringBuffer.append("剩余错误次数").append(CacheConstants.LOGIN_ERROR_COUNT - errorCount);
            }
        }
        return stringBuffer.toString();
    }
    public void loginSuccess(String userName){
        String errorKey = CacheConstants.LOGIN_ERROR + userName;
        // 登录成功，清空错误计数
        RedisUtil.deleteObject(errorKey);
    }
}
